define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'classroom/test/index' + location.search,
                    add_url: 'classroom/test/add',
                    edit_url: 'classroom/test/edit',
                    del_url: 'classroom/test/del',
                    multi_url: 'classroom/test/multi',
                    import_url: 'classroom/test/import',
                    table: 'classroom_test',
                }
            });

            var table = $("#table");

            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone,.btn-edit,.btn-add").data("area", ["95%","95%"]);
                $(".btn-editone,.btn-edit,.btn-add").data("shade", 0.5);
            });

            // 查看课程
            $(document).on("click",".show_course",function () {
                let ids = $(this).attr('data-id');
                Fast.api.open('classroom/course/show?ids='+ids,'查看');
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'course_id', title: __('Course_id'),
                            formatter: function (value, row, index) {
                                if(value){
                                    return `<bottom class="btn btn-xs btn-info show_course" data-id="${value}"><i class="fa fa-book"></i>&nbsp;&nbsp;ID：${value}</bottom>`;
                                } else {
                                    return '<span class="btn btn-xs btn-primary disabled">无</span>';
                                }
                            }
                        },
                        {field: 'title', title: __('Title'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {
                            field: 'countQuestion', title: __('题目编辑'), operate: false, table: table, class: 'autocontent',
                            formatter: function (value, row, index) {
                                let num = value > 0 ? `<b style="color: #26ffb6;">（${value}）</b>` : '';
                                return `<a href="classroom/test/question_list?ids=${row.id}" class="btn btn-xs btn-success btn-dialog" data-area="[&quot;95%&quot;,&quot;95%&quot;]" data-shade="[0.5,&quot;#000&quot;]" title="题目管理"><i class="fa fa-pencil"></i> 题目编辑${num}</a>`;
                            }
                        },
                        {
                            field: 'countTestLog', title: __('交卷信息'), operate: false, table: table, class: 'autocontent',
                            formatter: function (value, row, index) {
                                let num = value > 0 ? `<b style="color: #26ffb6;">（${value}）</b>` : '';
                                return `<a href="classroom/test_log/index?test_id=${row.id}" class="btn btn-xs btn-info btn-dialog" data-area="[&quot;95%&quot;,&quot;95%&quot;]" data-shade="[0.5,&quot;#000&quot;]" title="交卷列表"><i class="fa fa-file-text-o"></i> 交卷列表${num}</a>`;
                            }
                        },
                        {
                            field: 'countAssign', title: __('指定必考人员'), operate: false,
                            formatter: function (value, row, index) {
                                return `<a href="classroom/test/user_assign?ids=${row.id}" class="btn btn-xs btn-info btn-dialog" data-area="[&quot;95%&quot;,&quot;95%&quot;]" data-shade="[0.5,&quot;#000&quot;]" title="指定必考人员"><i class="fa fa-group"></i> ${value} 人</a>`;
                            }
                        },
                        {
                            field: 'pass_score', title: __('Pass_score'), operate: false
                        },
                        {
                            field: 'retake', title: __('Retake'), searchList: {"1":__('Retake 1'),"0":__('Retake 0')}, formatter: Table.api.formatter.toggle
                        },
                        {field: 'start_time', title: __('Start_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'end_time', title: __('End_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'status', title: __('Status'), searchList: {"1":__('Status 1'),"0":__('Status 0')}, formatter: Table.api.formatter.status},
                        {field: 'weigh', title: __('Weigh'), operate: false,visible:false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime,visible:false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        show: function () {
            Controller.api.bindevent();
        },
        user_assign: function () {
            $("#set_group").click(function () {
                $.ajax({
                    type:"POST",
                    dataType:"json",
                    data:{
                        actions:"set_group",
                        group_id: $("#user_g").val()
                    },
                    success: function (res) {
                        if(res.code === 1){
                            Toastr.success(res.msg);
                            setTimeout(()=>{
                                location.reload();
                            },800);
                        } else {
                            Toastr.error(res.msg);
                        }
                    }
                });
            });
            $("#truncate").click(function () {
                let index = layer.confirm("确认是否清空指定所有人？",{},function () {
                    layer.close(index);
                    $.ajax({
                        type:"POST",
                        dataType:"json",
                        data:{
                            actions:"truncate",
                        },
                        success: function (res) {
                            if(res.code === 1){
                                Toastr.success(res.msg);
                                setTimeout(()=>{
                                    location.reload();
                                },800);
                            } else {
                                Toastr.error(res.msg);
                            }
                        }
                    });
                });
            });

            var table = $("#user_table");
            table.bootstrapTable({
                toolbar: ".toolbar", //工具栏
                data: Config.user_assign,
                pk: 'id',
                sortName: 'weigh',
                showExport: true,
                columns: [
                    {field: 'nickname', title: '用户'},
                    {
                        field: 'status', title: '考试状态',
                        formatter: function (value, row, index) {
                            if(value === "完成"){
                                return  `<span class="text-success">${value}</span>`;
                            } else {
                                return `<span class="text-danger">${value}</span>`;
                            }
                        }
                    },
                ]
            });
            Table.api.bindevent(table);

            Controller.api.bindevent();
        },
        question_list: function() {
            Table.api.init({
                extend: {
                    index_url: 'classroom/question/index' + location.search,
                    add_url: 'classroom/question/add',
                    edit_url: 'classroom/question/edit',
                    del_url: 'classroom/question/del',
                    table: 'classroom_question',
                }
            });

            var table = $("#table");

            //当表格数据加载完成时
            table.on('load-success.bs.table', function (e, data) {
                let html = '（ ';
                for(const item of data.extent.list) {
                    html += `${item.name}：<b style="color: #f75444;">${item.num}</b> 道；`;
                }
                html += `总分：<b style="color: #f75444;">${data.extent.total_score}</b> ）`;
                $("#extent_text").html(html);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                showExport: false,
                pageSize: 50,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('QuestionTitle'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'type', title: __('QuestionType'), searchList: {"1":__('QuestionType 1'),"2":__('QuestionType 2'),"3":__('QuestionType 3'),"4":__('QuestionType 4'),"5":__('QuestionType 5')}, formatter: Table.api.formatter.normal},
                        {field: 'answer', title: __('QuestionAnswer'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'score', title: __('QuestionScore'),visible:false},
                        {field: 'weigh', title: __('QuestionWeigh'), operate: false,visible:false},
                        {field: 'operate', title: __('操作'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {
                // 导航切换
                $("#tablist li").click(function () {
                    let index = $(this).index();
                    $("#tablist li").removeClass("active");
                    $("#tablist li:eq("+index+")").addClass("active");
                });

                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});